//
//  GDMNetworkingTools.swift
//  SinaWeibo
//
//  Created by mac on 15/12/3.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

import AFNetworking

private let hostName = "https://api.weibo.com/"

private let dataErrorDomain = "com.baidu.data.error"

enum HTTPMethod : String {
    
    case POST = "POST"
    
    case GET = "GET"
}

//enum HTTPMethod: String {
//    case POST = "POST"
//    case GET = "GET"
//}

class GDMNetworkingTools: AFHTTPSessionManager {

    static let sharedTools : GDMNetworkingTools = {
        
        let url = NSURL(string: hostName)
        
        let tools = GDMNetworkingTools(baseURL: url)
//它本身是没有这一种格式的，所以自定义的时候要添加        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    func requestJSONDict(methed : HTTPMethod ,urlString : String , parameters : [String : AnyObject]? , finished : (result : [String : AnyObject]? , error : NSError?) -> () ){
      
        if methed == HTTPMethod.GET{
            
            GET(urlString, parameters: parameters, success: { (_, result) -> Void in
                
                if let dict = result as? [String : AnyObject]{
                    
//                   执行成功
                    finished(result: dict, error: nil)
                    
//                    数据结果返回要是正确的，返回回去的时候，也要进行一个return要不然他会是会向下面执行的，在执行就是错误的信息了
                    return
                }
                
//                执行失败,回调的结果不是一个字典NSLocalizedDescriptionKey本地化的描述信息
                let error = NSError(domain: dataErrorDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据格式错误"])
                
                finished(result: nil, error: error)
                
                }, failure: { (_, error) -> Void in
                    
                    finished(result: nil, error: error)
                    
            })
            
        }else{
            
          POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            if let dict = result as? [String : AnyObject]{
                
                //                   执行成功
                finished(result: dict, error: nil)
                
            }
            
            //                执行失败,回调的结果不是一个字典NSLocalizedDescriptionKey本地化的描述信息
            let error = NSError(domain: dataErrorDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据格式错误"])
            
            finished(result: nil, error: error)
            
            }, failure: { (_, error) -> Void in
                
                 finished(result: nil, error: error)
                
          })
        
    }
}
}
